package com.xjtu.duansheli.interceptor;


import com.xjtu.duansheli.exception.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
public class CustomHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        log.info("进入拦截器，url=" + url);
        Object user = request.getSession().getAttribute("loginUser");
        log.info(String.valueOf(user));
        if (user == null) {
            throw new MyException(100, "未登录");
//            return false;
//            log.info("未登陆或者登陆失效！");
//            if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
//                //ajax请求
//                Map<String, String> ret = new HashMap<String, String>();
//                ret.put("type", "error");
//                ret.put("msg", "登录状态已失效，请重新去登录!");
//                response.getWriter().write(JSONObject.fromObject(ret).toString());
//                return false;
//            }
//            response.sendRedirect(request.getContextPath() + "/login/");
//            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        log.info("postHandle:请求后调用");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        log.info("afterCompletion:请求调用完成后回调方法，即在视图渲染完成后回调");
    }

}
